<template>
  <div class="Role">
    <div class="page-head">
      <div class="page-title">
        程序列表
      </div>
      <div class="page-tool">
        <div class="tool-btn" v-if="$permiss(btnPermiss, '上传版本')" @click="open('add')">上传版本</div>
      </div>
      
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe>
            <el-table-column
              width="20"
            />
            <el-table-column
              prop="name"
              label="程序名称"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="version"
              label="版本号"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="create_time"
              label="上传时间"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="model_name"
              label="适配机型"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="{row}">
                <div class="operation-col">
                  <div class="txt-btn error" v-if="$permiss(btnPermiss, '删除')" @click="doDelete(row)">删除</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div  class="page-footer">
        <pagina-tion
        class="page-pager"
        v-show="total>=0"
        :background="true"
        :total="total"
        :offset.sync="offset"
        :limit.sync="limit"
        @pagination="getChangePage"
      />
      <button class="page-button">确定</button>

      </div>
     
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog :visible.sync="model.visible" width="450px" title="上传版本" :close-on-click-modal="false" :show-close="false">
      <div class="dialog-body">
        <el-form ref="form" :model="form" label-width="100px" label-position="left">
          <el-form-item label="程序名称" class="required">
            <el-input
              v-model="form.name"
              name="programName"
              placeholder="请填写程序名称"
              v-validate="'required|maxLength32'"
            />
            <div v-show="errors.has('programName')" class="el-form-item__error">{{ errors.first('programName') }}</div>
          </el-form-item>
          <el-form-item label="更新包" class="upload-form-item required">
            <el-input
              :readonly="true"
              placeholder="请选择要上传的文件"
              v-model="fileName"
              name="programUrl"
              v-validate="'required'"
            />
            <input
              type="file"
              class="file-input"
              accept="application/zip, application/vnd.android.package-archive, application/octet-stream, .msi, .exe"
              ref="fileInput"
              @change="fileChange($event)"
            >
            <img src="~assets/img/pick.png" class="pick-img">
            <div v-show="errors.has('programUrl')" class="el-form-item__error">{{ errors.first('programUrl') }}</div>
          </el-form-item>
          <el-form-item label="版本号" class="required">
            <el-input
              v-model="form.version"
              name="version"
              placeholder="请填写版本号"
              v-validate="'required|maxLength32'"
            />
            <div v-show="errors.has('version')" class="el-form-item__error">{{ errors.first('version') }}</div>
          </el-form-item>
          <el-form-item label="适配机型" class="required">
            <el-select
              class="form-sel"
              v-model="form.model_id"
              name="model_id"
              placeholder="请选择适配机型"
              v-validate="'required'"
            >
              <el-option v-for="item in modelSel" :key="item.model_id" :label="item.name" :value="item.model_id"></el-option>
            </el-select>
            <div v-show="errors.has('model_id')" class="el-form-item__error">{{ errors.first('model_id') }}</div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico"
             src="~assets/img/warning.png">
        <div class="comfirm-txt">
          <div>
            确定删除该条数据？
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="programDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import * as api from '@/api'
import { limit,middleLimit } from '@/consts/consts'
import { programFormKey } from '@/consts/formKey'
import { md5 } from '@/utils/md5'
import client from '@/utils/oss'
export default {
  data() {
    return {
      btnPermiss: [],
      limit:document.body.clientHeight>= 770 ? limit : middleLimit,
      total: 0,
      offset: 0,
      tableData: [],
      model: {
        type: 'add',
        visible: false
      },
      modelSel: [],
      program_id: '',
      form: {
        ...programFormKey
      },
      visibility: false,
      fileName: '',
      fileSize: '',
      loading: null
    }
  },
  methods: {

    open(type) {
      this.$validator.reset()
      this.model.type = type
      this.model.visible = true
    },
    
    getChangePage(val) {
      this.offset = val.offset
      this.programList()
    },

    
    fileChange(e) {
      let file = this.$refs.fileInput.files[0];
      let index = file.name.lastIndexOf(".")
      let suf = file.name.substr(index+1)
      console.log('后缀名是： ', suf)
      const typeOk = ['zip', 'ZIP', 'apk', 'exe', 'msi'].includes(suf)
      if (typeOk) {
        this.fileSize = file.size
        this.loading = Loading.service({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        md5(file).then(res => {
          this.fileName = file.name
          this.form.md5 = res
          let formData = new FormData()
          formData.append('bucket', 'program')
          formData.append('file', file)
          this.upload(file)
        })
      } else {
        this.$message.warning('只能上传zip、apk、exe、msi格式的文件')
      }
      
      
    },

    
    doDelete(row) {
      this.program_id = row.program_id
      this.visibility = true
    },
    
    close() {
      this.model.visible = false
      this.form = {...programFormKey}
      this.fileName = ''
      
    },
    
    submit() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.addOrEdit()
        } else {
          this.$message.warning('有信息未填写正确')
        }
      })
    },
    
    async upload(file) {
      let arr = file.name.split(".")
      let [suf, ...rest] = [...arr].reverse()
      let n = rest.reverse().join('.')
      
      let fileName = `${n}_${+new Date}.${suf}`
      // this.ossPolicy(fileName, file)
      let result = await client.multipartUpload(`program/${fileName}`, file)
      
      if (result) {
        [this.form.url] = result.res.requestUrls[0].split('?') 
        this.fileName = file.name
        this.loading.close()
      }
    },
        
    async ossPolicy(fileName, file) {
      const { code, data } = await api.dropdown(this).ossPolicy({
        dir: 'program'
      });
      if (code === 0) {
        let formData = new FormData()
        formData.append('key', `program/${fileName}`) // 存储在oss的文件路径
        formData.append('OSSAccessKeyId', data.accessId) // //accessKeyId
        formData.append('policy', data.policy) // policy
        formData.append('Signature', data.signature) //签名
        formData.append('success_action_status', 200)
        formData.append('file', file, fileName)
        this.$axios.post(data.host, formData, {
          headers: { 
            'Content-Type': 'multipart/form-data'
          },
        }).then(res => {
          this.form.url = `${data.host}/program/${fileName}`
          this.fileName = this.file.name
          this.loading.close()
        })
      }
    },
    
    async modelList() {
      const { code, data } = await api.dropdown(this).modelList({
        exhibition: 1
      })
      if (code === 0) {
        this.modelSel = data
      }
    },
    
    // 程序列表
    async programList() {
      const { code, data, total } = await api.program(this).programList({
        offset: this.offset,
        limit:this.limit,
      })
      if (code === 0) {
        this.tableData = data
        this.total = total
      }
    },
    
    async addOrEdit() {
      let fn = this.model.type === 'add' ? 'programAdd' : 'programUpdate'
      this.form.size = Math.ceil(this.fileSize / 1024 / 1024).toString()
      const { code } = await api.program(this)[fn](this.form, this.program_id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.close()
        this.programList()
      }
    },

    async programDelete() {
      const { code } = await api.program(this).programDelete(this.program_id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.program_id = ''
        this.visibility = false
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit
          }
        }
        this.programList()
      }
    },
  },
  created () {
    this.modelList()
    this.programList()
    let permission = JSON.parse(localStorage.getItem('permission'))
    let curMenu = permission.find(item => item.txt === "程序更新")
    this.btnPermiss = curMenu.btns
  },
}
</script>

<style lang="stylus">
.Program {

}
</style>